
import { regView, BaseView } from "../../../extensions/cocos-scaffold-3x/assets/ui/base/BaseView";
import { EBundleName, gg } from "../../Game";

import { _decorator, Component, EventTouch, game, Label, log, Node, Vec3 } from 'cc';
import { MathUtils } from "../common/MathUtils";
import { GameplayComponent } from "./GameplayComponent";
import { GpEcsWorld } from "./m/GpEcsWorld";
import { Sglt } from "./m/SgltDefine";
import GpWorld from "./v/GpWorld";
import { Comp } from "./m/CompDef";
import { GpCmdSystem, GpCmdType, GpCmdDataDef } from "./m/systems/CmdSystem";
import { AudioManager } from "../../common/AudioManager";
const { ccclass, property } = _decorator;
@regView({
    bundle: "subBundle",
    prefabPath: "gameplay/ViewGameplay"
})

@ccclass
export default class ViewGameplay extends BaseView {
    worldInfo: Sglt.WorldInfo
    ecsWorld: GpEcsWorld
    gpWorld: GpWorld

    // @property(Label)
    // lbEntityCount: Label = null;
    // @property(Label)
    // lbFrameCount: Label = null;



    async onOpen() {
        game.frameRate = 65

        this.ecsWorld = new GpEcsWorld()


        await AudioManager.instance().loadAudios("gameplay/sound", EBundleName.subBundle)
        this.worldInfo = this.ecsWorld.getSingleton(Sglt.WorldInfo)
        await this.ecsWorld.init()
        this.gpWorld = this.node.getComponentInChildren(GpWorld)
        //@ts-ignore
        this.node.getComponentsInChildren(GameplayComponent).forEach(
            (i) => i.init(this)
        )
        console.log("ViewGameplay onOpen", this.ecsWorld, this.gpWorld);



    }

    protected onEnable(): void {
        console.log("ViewGameplay onEnable", this.ecsWorld, this.gpWorld);
    }



    update(deltaTime: number) {

        // if(this.ecsWorld.frameCount>100){return}
        if (!this.ecsWorld?.enable) { return }
        this.updateEcsWorld(deltaTime, this.ecsWorld)
        this.refreshUI()
        // if(!this.prop&&this.ecsWorld.frameCount==1000){
        //     this.onTouchSave()
        //     alert("1️⃣自动保存")
        // }
    }

    updateEcsWorld(deltaTime: number, ecsWorld: GpEcsWorld) {
        const deltaMs = MathUtils.fixNumber(deltaTime * 1000)
        if (this.worldInfo.isMaster) {
            // ecsWorld.update(deltaMs)
            ecsWorld.update(ecsWorld.elapsedMsPerFrame)
        } else {
            /**如果主机帧数比自己快了120帧,则同步到当前帧数+100 */
            // if (this.worldInfo.masterFrameCount - ecsWorld.frameCount > 120) {
            //     ecsWorld.synFrame(ecsWorld.frameCount + 100)
            // }
            // const newframe = Math.floor((deltaMs + ecsWorld._left_elapsed) / ecsWorld.elapsedMsPerFrame)
            // if (this.worldInfo.masterFrameCount > ecsWorld.frameCount + newframe) {
            //     ecsWorld.update(deltaMs)
            // }
        }

        this.gpWorld.updateAllEntityTransform()
    }

    refreshUI() {

        // this.lbEntityCount.string = Object.keys(this.ecsWorld.entities).length.toString()
        // this.lbFrameCount.string = this.ecsWorld.frameCount + ""
    }

    onClose(): void {

        this.ecsWorld.destory()
    }

    onTouchSave(evt: EventTouch) {

        // gg.storage(GamePlayStorage).data.ecsSnapshot = EcsWorldSnapshot.fromWorld(this.ecsWorld)
        // gg.storage(GamePlayStorage).save()
    }

    lastJoystickDirection: Vec3 = new Vec3(0, 0, 0)

    // onJoyStickMove(stick: VisualJoyStick, info: { direction: Vec3, radian: number }) {
    //     if (info.direction.equals(this.lastJoystickDirection)) {
    //         return
    //     }

    //     this.setDirection(info.direction.clone())
    //     // console.log("onJoyStickMove", info.direction.x, info.direction.y);

    //     this.lastJoystickDirection.set(info.direction)

    // }


    setDirection(direction: Vec3) {
        // if (direction.x == 0 && direction.y == 0) {
        //     //方向为0
        //     return
        // }
        const currentControlEntity = this.ecsWorld.entities[10000]
        if (!currentControlEntity) {
            //实体不存在
            return
        }
        const targetDirection = currentControlEntity.component(Comp.Move).targetDirection
        if (direction.x == targetDirection.x && direction.y == targetDirection.y) {
            /**方向没变化 */
            return
        }

        this.ecsWorld.system(GpCmdSystem).makeCmd(
            GpCmdType.changeTargetDirection,
            new GpCmdDataDef.ChangeTargetDirection(
                currentControlEntity.id,
                direction
            )
        )
    }
}
